package com.wlc.config;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 王立朝
 * @date 2024/7/3
 * @description:
 */
public class PlatformInterceptor  implements HandlerInterceptor {
	// 这里假设通过请求头中的某个字段来判断是PC端还是APP端
	private static final String HEADER_PLATFORM_TYPE = "X-Platform-Type";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 获取平台类型，这里简化处理，实际情况可能更复杂
		String platformType = request.getHeader(HEADER_PLATFORM_TYPE);
		if ("app".equalsIgnoreCase(platformType)) {
			// 设置到ThreadLocal，这样在同一个线程内的后续操作都能访问到
			PlatformContextHolder.setPlatform("APP");
		} else {
			PlatformContextHolder.setPlatform("PC");
		}
		return true; // 继续执行请求链
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		// 可以在这里进行一些后处理操作，但通常不需要处理平台信息
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		// 清理ThreadLocal，避免内存泄漏
		PlatformContextHolder.remove();
	}

}
